<?php

namespace App\Service\Common;

use App\Model\Common\SettingModel;
use App\Service\BaseService;
use Hyperf\Di\Annotation\Inject;

class SettingService extends BaseService
{

    #[Inject]
    protected SettingModel $settingModel;

    public function pageListForAdmin($params=[], $page=1, $ps=10)
    {
        $lists = $this->settingModel->pageListForAdmin($params, $page, $ps)->toArray();
        foreach ($lists['data'] as &$item){
            if ($item['ext']){
                $item['ext'] = json_decode($item['ext']);
            }
        }
        return $lists;
    }

    public function addOne($params)
    {
        $codeEx = $this->settingModel->findByCode($params['code'],['id']);
        if ($codeEx){
            return [false,'code已存在'];
        }
        $r = $this->settingModel->addOne($params);
        if (!$r){
            return [false,'添加失败'];
        }
        $this->settingModel->setCache($params['code'], $params['val']);
        return [true,'添加成功'];
    }

    public function updateSetting($id, $data)
    {
        $codeEx = $this->settingModel->findById($id,['id','code']);
        if (!$codeEx){
            return [false,'数据不存在'];
        }
        $r = $this->settingModel->updateVal($id, $data['val']);
        if (!$r){
            return [false,'没有改变'];
        }
        $this->settingModel->setCache($codeEx->code, $data['val']);
        return [true,'更新成功'];
    }

    public function delSettingByIds($ids)
    {
        $codes = $this->settingModel->getSomeByIds($ids,['id','code']);
        if ($codes->isEmpty()){
            return [false,'数据不存在'];
        }
        $r = $this->settingModel->delByIds($ids);
        if (!$r){
            return [false,'删除失败'];
        }
        $this->settingModel->delSomeCacheByCodes($codes->pluck('code')->toArray());
        return [true,'删除成功'];
    }

    public function refreshAll()
    {
        $allCodes = $this->settingModel->getAll([],['code','val']);
        // 一般建议直接删除cache
//        $this->settingModel->delSomeCacheByCodes($allCodes->pluck('code')->toArray());
        foreach ($allCodes as $item){
            $this->settingModel->setCache($item->code, $item->val);
        }
        return [true,'刷新成功'];
    }
}